from fastapi import APIRouter, HTTPException, Query
from typing import List, Optional
from pydantic import BaseModel
from utils import employees_curd
import sqlite3

router = APIRouter(
    tags=["employees"]
)

class EmployeeBase(BaseModel):
    employee_id: str
    name: str
    affiliation: str
    dept1: str
    dept2: str
    dept3: str
    position: str
    hire_date: str
    leave_date: Optional[str] = None

class EmployeeCreate(EmployeeBase):
    pass

class Employee(EmployeeBase):
    class Config:
        from_attributes = True

@router.get("/", response_model=List[Employee])
async def get_employees():
    """获取所有员工信息"""
    return employees_curd.get_all_employees()

@router.get("/search", response_model=List[Employee])
async def search_employees(
    query: str = Query(..., description="搜索关键词，支持工号或姓名模糊搜索"),
    limit: int = Query(20, description="最大返回结果数量")
):
    """
    搜索员工
    
    - **query**: 搜索关键词，支持工号或姓名模糊搜索
    - **limit**: 最大返回结果数量，默认20
    """
    return employees_curd.search_employees(query, limit)

@router.get("/{employee_id}", response_model=Employee)
async def get_employee(employee_id: str):
    """获取指定员工信息"""
    employee = employees_curd.get_employee(employee_id)
    if not employee:
        raise HTTPException(status_code=404, detail="Employee not found")
    return employee

@router.post("/", response_model=Employee)
async def create_employee(employee: EmployeeCreate):
    """创建新员工"""
    try:
        return employees_curd.create_employee(employee.dict())
    except sqlite3.IntegrityError:
        raise HTTPException(status_code=400, detail="Employee ID already exists")

@router.put("/{employee_id}", response_model=Employee)
async def update_employee(employee_id: str, employee: EmployeeCreate):
    """更新员工信息"""
    updated_employee = employees_curd.update_employee(employee_id, employee.dict())
    if not updated_employee:
        raise HTTPException(status_code=404, detail="Employee not found")
    return updated_employee

@router.delete("/{employee_id}")
async def delete_employee(employee_id: str):
    """删除员工"""
    if not employees_curd.delete_employee(employee_id):
        raise HTTPException(status_code=404, detail="Employee not found")
    return {"message": "Employee deleted successfully"}

@router.post("/batch", response_model=List[Employee])
async def batch_create_employees(employees: List[EmployeeCreate]):
    """批量创建员工"""
    try:
        employees_data = [employee.dict() for employee in employees]
        return employees_curd.batch_create_employees(employees_data)
    except sqlite3.IntegrityError:
        raise HTTPException(status_code=400, detail="One or more employee IDs already exist")
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e)) 